package com.work.daily;

import java.util.*;

/**
 * title : 二叉树的层次遍历 II
 * solution : 广度优先遍历 BFS
 * link : https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
 * Created by suk on 2020/9/6.
 */
public class D9_LevelOrderBottom_107_01 {

    public static void main(String[] args) {

        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(2);
        node.right = new TreeNode(3);
        node.left.left = null;
        node.left.right = new TreeNode(5);

        D9_LevelOrderBottom_107_01 d9 = new D9_LevelOrderBottom_107_01();
        System.out.println(d9.levelOrderBottom(node));
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {

        List<List<Integer>> result = new ArrayList<>();

        if (root == null)
            return result;

        Queue<TreeNode> levelSave = new LinkedList<>();
        levelSave.add(root);

        List<Integer> temp;
        while (!levelSave.isEmpty()) {
            temp = new ArrayList<>();
            int size = levelSave.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = levelSave.poll();

                temp.add(node.val);
                if (node.left != null) {
                    levelSave.add(node.left);
                }
                if (node.right != null) {
                    levelSave.add(node.right);
                }
            }
            // 这一点没考虑到.需要每次插到队列头
            result.add(0, temp);
        }

        return result;
    }

    private static class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode(int x) { val = x; }
    }

}
